<template>
  <create-frame title="修改售后工单" @submit="onSubmit">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-suffix=":" inline
      label-position="right">
      <el-form-item class="form-item" label="创建人">
        <el-input disabled :model-value="detail?.order.cuser"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="创建时间">
        <el-input disabled :model-value="detail?.order.ctime"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="维修单号" prop="orderNumber">
        <el-input disabled v-model="form.orderNumber"></el-input>
        <!-- <el-button type="primary" link @click="getOrderNumber">重新获取</el-button> -->
      </el-form-item>
      <el-form-item class="form-item" label="客户名称" prop="customerCode">
        <zw-select :data="customerList" label-key="name" value-key="code" v-model:value="form.customerCode"
          v-model:label="form.customerName"></zw-select>
      </el-form-item>
      <el-form-item class="form-item" label="站点名称" prop="siteName">
        <el-input v-model="form.siteName"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="联系人" prop="contactor">
        <el-input v-model="form.contactor"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="联系电话" prop="telephone">
        <el-input v-model="form.telephone"></el-input>
      </el-form-item>
      <el-form-item class="form-item-line" label="联系地址" prop="address">
        <el-input v-model="form.address"></el-input>
      </el-form-item>
      <el-form-item class="form-item" label="接收快递日期" prop="receiveDate">
        <zw-date-picker v-model="form.receiveDate" />
      </el-form-item>
      <el-form-item class="form-item" label="接收快递单号" prop="logisticsNumber">
        <el-input v-model="form.receiveNumber"></el-input>
      </el-form-item>
      <el-form-item class="form-item-line" label="备注" prop="comment">
        <el-input type="textarea" :rows="4" v-model="form.comment"></el-input>
      </el-form-item>
      <el-form-item class="form-item-line" label="附件">
        <file-gallary :readonly="false" :file-list="files" @upload="onFileUpload" @remove="onFileRemove"></file-gallary>
      </el-form-item>
    </el-form>
    <create-list-frame :inner-control="true" title="产品设备" :columns="columns" :table-data="tableData"
      :total="tableData.length">
      <template #buttons>
        <el-button type="primary" @click="currentProduct = null; createProductViewVisible = true;">添加产品</el-button>
        <create-product-view :visible="createProductViewVisible" :data="currentProduct" @save="onCreateProductSaved"
          @close="createProductViewVisible = false"></create-product-view>
      </template>
      <template #operations="row">
        <el-button v-if="!isProcessing" link type="primary"
          @click="currentProduct = row.value; createProductViewVisible = true;">编辑</el-button>
        <el-button v-if="!isProcessing" link type="danger" @click="onDeleteProduct(row)">删除</el-button>
      </template>
    </create-list-frame>
  </create-frame>
</template>
<script lang="ts" setup>
import CreateFrame from '@/components/CeateFrame/CreateFrame.vue';
import CreateProductView from './CreateProductView.vue';
import ZwSelect from '@/components/Form/ZwSelect.vue';
import ZwDatePicker from '@/components/Form/ZwDatePicker.vue';
import CreateListFrame from '@/components/CeateFrame/CreateListFrame.vue';
import FileGallary from '@/components/Form/FileGallary.vue';
import DateUtil from '@/plugins/date';
import ApiTree from '@/server/api-tree';
import { DictTypeEnum, type DictVO } from '@/server/dict/types';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, reactive, ref, useTemplateRef } from 'vue';
import type { ColumnType } from '@/components/types';
import ElConfirm from '@/components/ElConfirm';
import emits, { EventEnum } from '@/plugins/emits';
import { type OrderDetailDTO, type CreateOrderProductVO, type CreateOrderVO } from '@/server/afterSale/types';
import { useRoute } from 'vue-router';
import WinUtil, { WinNameRecord } from '@/plugins/window';
import type { FileInfoDTO } from '@/server/file/types';
import type { UserVO } from '@/server/user/types';
import StoreManager from '@/plugins/storage';

const route = useRoute();
const guid = ref<string>(route.query.guid?.toString() || "")

const form = ref<CreateOrderVO>({
  guid: "",
  orderNumber: "",
  customerCode: "",
  customerName: "",
  siteName: "",
  contactor: "",
  telephone: "",
  address: "",
  receiveDate: "",
  receiveNumber: "",
  products: [],
  files: [],
  comment: ""
});
const fomrRef = useTemplateRef<FormInstance>('formRef')

const productsValidator = () => {
  if (!form.value.products) {
    return "产品数据不能为空";
  }
  if (form.value.products.length === 0) {
    return "产品数据不能为空";
  }
  const errorMsg = [] as string[];
  form.value.products.forEach((x, index) => {
    const val = x as CreateOrderProductVO;
    if (!val.productSn || !val.productCode) {
      errorMsg.push(`第${index + 1}行数据填写不完整！`);
    }
  })
  if (errorMsg.length > 0) {
    return errorMsg.join(";");
  }
  return "";
}
const rules = reactive<FormRules<CreateOrderVO>>({
  orderNumber: [{ required: true, message: "订单编号不能为空" }],
  customerCode: [{ required: true, message: "客户不能为空" }],
  siteName: [{ required: true, message: "站点不能为空" }],
  contactor: [{ required: true, message: "联系人不能为空" }],
  telephone: [{ required: true, message: "联系电话不能为空" }],
  address: [{ required: true, message: "联系地址不能为空" }],
  receiveDate: [{ required: true, message: "快递接收日期不能为空" }],
  receiveNumber: [{ required: true, message: "快递单号不能为空" }]
})
/** 获取客户主体 */
const customerList = ref<DictVO[]>([]);
const getCustomerList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.CUSTOMER, true);
  if (success) {
    customerList.value = data;
  }
}
/** 产品表格 */
const columns = [
  { prop: "productName", colName: "产品名称", width: 0 },
  { prop: "productSn", colName: "SN", width: 0 },
  { prop: "comment", colName: "备注", width: 0 },
  { prop: "repairCount", colName: "维修次数", width: 0 },
  { prop: "shippingDate", colName: "出货日期", width: 0 },
] as ColumnType[];
const tableData = ref<(CreateOrderProductVO & { repairCount: number, shippingDate: string })[]>([])
const createProductViewVisible = ref(false)
const currentProduct = ref<CreateOrderProductVO | null>(null);

const onCreateProductSaved = async (data: CreateOrderProductVO) => {
  const product = tableData.value.find(x => x.guid === data.guid);
  if (!product) {
    if (tableData.value.some(x => x.productSn === data.productSn)) {
      ElMessage.error("SN已存在");
      return;
    }
    const { success, data: d } = await ApiTree.afterSaleOrder.getRepairCount(data.productSn);
    const { success: f, data: s } = await ApiTree.shipping.getShippingDate(data.productSn);
    tableData.value.push({ ...data, repairCount: success ? d : 0, shippingDate: f ? DateUtil.resolve(s, true) : "" });
  } else {
    if (tableData.value.some(x => x.productSn === data.productSn && x.guid !== data.guid)) {
      ElMessage.error("SN已存在");
      return;
    }
    product.productCode = data.productCode;
    product.productName = data.productName;
    product.productSn = data.productSn;
    product.comment = data.comment;
    const { success, data: d } = await ApiTree.afterSaleOrder.getRepairCount(data.productSn);
    const { success: f, data: s } = await ApiTree.shipping.getShippingDate(data.productSn);
    product.repairCount = success ? d : 0;
    product.shippingDate = f ? DateUtil.resolve(s, true) : "";
  }
  createProductViewVisible.value = false;
}
const onDeleteProduct = (row: { value: CreateOrderProductVO }) => {
  const m = row.value;
  ElConfirm(`确定要删除产品【${m.productSn}】吗？`).then(() => {
    const index = tableData.value.findIndex(x => x.guid === m.guid);
    tableData.value.splice(index, 1);
  }).catch();
}
/** 附件 */
const files = ref<FileInfoDTO[]>([]);
const onFileUpload = async (fileIds: string[]) => {
  const { success, data } = await ApiTree.file.getFileInfo([fileIds[0]]);
  if (success && data && data.length > 0) {
    files.value.push(data[0]);
  }
}
const onFileRemove = (fileId: string) => {
  const index = files.value.findIndex(x => x.guid === fileId);
  if (index > -1) {
    files.value.splice(index, 1);
  }
}
/** 提交表单 */
const onSubmit = () => {
  fomrRef.value?.validate(async (valid) => {
    if (valid) {
      form.value.products = tableData.value;
      const err = productsValidator()
      if (err !== "") {
        ElMessage.error(err);
        return;
      }
      form.value.files = files.value.map(x => x.guid);
      const { success, msg } = await ApiTree.afterSaleOrder.update(form.value);
      if (success) {
        ElMessage.success(msg);
        setTimeout(() => {
          emits.triggerOwner(EventEnum.TABLE_RELOAD);
          WinUtil.open("/afterSale/order/detail?guid=" + guid.value, WinNameRecord.ORDER_DETAIL, guid.value).close();
        }, 300);
      }
    }
  })
}
/** 获取工单基本信息 */
const isProcessing = ref(false);
const user = ref<UserVO | null>(StoreManager.get<UserVO>("user"));
const detail = ref<OrderDetailDTO>();
const getDetail = async () => {
  const { success, data } = await ApiTree.afterSaleOrder.detail(guid.value);
  if (success) {
    detail.value = data;
    form.value = {
      ...data.order,
      files: data.fileList?.map(x => x.guid) || [],
      products: [...data.products]
    };
    tableData.value = data.products.map(x => {
      x.shippingDate = DateUtil.resolve(x.shippingDate, true);
      return x;
    });
    files.value = data.fileList || [];
    const isAdmin = user.value?.role === "ADMIN";
    isProcessing.value = !isAdmin && data.order.orderStatus !== "SUBMITTED";
  }
}
onMounted(() => {
  if (!guid.value) {
    ElMessage.error("缺少关键参数");
    setTimeout(() => {
      window.close();
    }, 200);
    return
  }
  getCustomerList();
  // getOrderNumber();
  getDetail();
})
</script>
<style lang="scss" scope>
.form-item {
  width: calc(100% / 2 - 32px);

  &-line {
    width: calc(100% - 32px);
  }
}
</style>
